const { STRING } = require('sequelize')
const { db } = require('../core/sequelize')
const { Sequelize, Model, transaction } = require('sequelize')
const { Posts } = require('./posts')
class Like extends Model {
    static async like(pid, uid) {
        const like = await Like.findOne({
            where: {
                uid: uid,
                pid: pid
            }
        })
        // 已存在就取消点赞
        if (like) {
            throw new Error('已点赞!')
            // throw new global.errs.NotFound("失败", NotFound.LIKE_FAIL)
        }
        // 注意 transaction在 new之后的sequerlize下
        return db.transaction(async t => {
            // 执行点赞表的插入数据
            await Like.create({
                uid,
                pid
            }, {
                transaction: t
            })
            // 帖子列表修改点赞数
            const postDetila = await Posts.getPostsDetila(pid)
            // increment 方法实现点赞数量自增
            await postDetila.increment('likeCount', {
                by: 1,
                transaction: t
            })
            return true
        })
    }
    // 先查询
    // static async userLikeIt(uid, bid) {
    //     const like = await Like.findOne({
    //         where: {
    //             bkid: bid,
    //             uid: uid
    //         }
    //     })
    //     return like ? true : false
    // }
}
Like.init(
    {
        id: {
            type: Sequelize.INTEGER,
            primaryKey: true, //设置主键
            autoIncrement: true,
        },
        uid: Sequelize.INTEGER, //类型 字符串
        pid: Sequelize.INTEGER, //类型 字符串
        createTime: { type: STRING, field: 'createTime' },
        updateTime: { type: STRING, field: 'updateTime' },
    },
    {
        // underscored: true,
        sequelize: db,
        modelName: 'like', timestamps: false
    },

)
module.exports = { Like }
